package com.erpanderp.wam.usm.model.service.leave;

import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.classic.Session;

import com.erpanderp.wam.usm.model.entity.leave.LeaveTypeRole;
import com.erpanderp.wam.util.HibernateUtil;

public class LeaveTypeRoleDAO {
	
	public LeaveTypeRole createLeaveTypeRole(LeaveTypeRole leaveTypeRole){
		System.out.println("IN CREATE LEAVE TYPE ROLE");
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.setFlushMode(FlushMode.AUTO);
			session.beginTransaction();
			session.save(leaveTypeRole);
			session.getTransaction().commit();
			return leaveTypeRole;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
			// TODO: handle exception
		}
	}
	public LeaveTypeRole getLeaveTypeRoleByRoleIdAndLeaveTypeId(Long leaveTypeid, Long roleId){
		LeaveTypeRole leaveTypeRole = new LeaveTypeRole();
		System.out.println(leaveTypeid+" "+roleId);
		System.out.println("IN CREATE LEAVE TYPE ROLE");
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.setFlushMode(FlushMode.AUTO);
			session.beginTransaction();
			String queryString = "from LeaveTypeRole ltr where ltr.leaveType.leaveTypeid = :leaveTypeid and ltr.role.roleId = :roleId";
			Query query = session.createQuery(queryString).setLong("leaveTypeid", leaveTypeid).setLong("roleId", roleId);
			leaveTypeRole = (LeaveTypeRole) query.uniqueResult();
			session.save(leaveTypeRole);
			session.getTransaction().commit();
			return leaveTypeRole;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
			// TODO: handle exception
		}
	}
	public List<LeaveTypeRole> getLeaveTypesListByRoleId(Long roleId){
		System.out.println("%%%%%%%%ROLE ID IS : "+roleId);
		List<LeaveTypeRole> leaveTypeRoleList = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.setFlushMode(FlushMode.AUTO);
			session.beginTransaction();
			String queryString = "from LeaveTypeRole ltr where ltr.role.roleId= :roleId";
			Query query = session.createQuery(queryString).setLong("roleId", roleId);
			leaveTypeRoleList =  query.list();
			System.out.println("%%%%%%%% LEAVE TYPES ROLES SIZE IS :"+leaveTypeRoleList.size()+"%%%%%%%%%");
			session.getTransaction().commit();
			return leaveTypeRoleList;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
			// TODO: handle exception
		}
	}

}
